﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.Core.Support;
using Microsoft.SharePoint;
using MS.InformationManagement.DAL.DocumentCenter;
using MS.InformationManagement.Core.TransactionsResponse;

namespace MS.InformationManagement.BLL.UserProfileManagement
{
    public class DeleteUserProfileCommand : ICommandWithResponse
    {
         #region private methods

        int _profileID;
        List<VincularPerfiles> _perfiles = new List<VincularPerfiles>();

        #endregion

        #region constructors

        public DeleteUserProfileCommand(int profileID)
        {
            _profileID = profileID;
        }

        #endregion

        #region Implemented Methods

        public ITransactionResponse Execute()
        {
            DeleteUserProfileCommandResponse response = new DeleteUserProfileCommandResponse();

            using (DCDocumentCenterDataContext ctx = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                VincularPerfiles profileToDelete = ctx.Perfiles.SingleOrDefault(profile => profile.Id.Equals(_profileID));
                if (profileToDelete != default(VincularPerfiles)) 
                { 
                    ctx.Perfiles.RecycleOnSubmit(profileToDelete); 
                }
                ctx.SubmitChanges();
                _perfiles.Add(profileToDelete);

                response.CurrentPerfil = profileToDelete;
                response.ResponseMessage = "Exito";
                response.Result = true;
            }

            return response;
        }

        public void Undo()
        {
            using (DCDocumentCenterDataContext ctx = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                foreach(VincularPerfiles perfil in _perfiles)
                {
                    VincularPerfiles newElement = new VincularPerfiles 
                    {
                        Title = string.Empty,
                        Perfil = perfil.Perfil,
                        ContribuyenteEnSitio = perfil.ContribuyenteEnSitio,
                        TipoRole = perfil.TipoRole
                    };

                    ctx.Perfiles.InsertOnSubmit(newElement);
                    ctx.SubmitChanges();
                }
            }
        }

        #endregion
    }
}
